package com.gongpingjialoan.network;

import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.NetworkError;
import com.android.volley.NetworkResponse;
import com.android.volley.NoConnectionError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.RetryPolicy;
import com.android.volley.ServerError;
import com.android.volley.TimeoutError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.gongpingjialoan.api.API;
import com.gongpingjialoan.data.KCookie;
import com.gongpingjialoan.global.GPJApplication;
import com.gongpingjialoan.utility.CRequest;
import com.gongpingjialoan.utility.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2015/9/16.
 */
public class NetDataJson {
    //测试环境
//    public static String SERVER_DOMAIN = "http://preapi8.gongpingjia.com";

    //生产环境
    public static String SERVER_DOMAIN = "http://api8.gongpingjia.com";

    //开发环境
//    public static String SERVER_DOMAIN = "http://192.168.1.82:8000";

    public static final String errString = "数据异常，请检查网络连接或稍后重试。";
    //测试环境
//    public static final String LOAN_SERVER_DOMAIN = "http://preloan.gongpingjia.com";

    //生产环境
    public static final String LOAN_SERVER_DOMAIN = "http://loan.gongpingjia.com";

    //新车活动生产环境
    public static final String NEWCAR_SERVER_DOMAIN = "http://tesla.gongpingjia.com";

    //新车活动测试环境
//    public static final String NEWCAR_SERVER_DOMAIN = "http://pretesla.gongpingjia.com";

    //车分期感兴趣域名
    public static final String DOMAIN_INTERESTS = "http://instalment.gongpingjia.com";

    private Map<String, Object> paramsMap;

    private final static int REQUEST_TIMEOUT = 20000;

    public NetDataJson.OnNetDataJsonListener mListener;

    public NetDataJson.OnStringListener stringListener;

    private StringRequest stringRequest;

    private String url;

    public String postType = "ambiguous";

    private int type = 0;

    private long cacheTime;

    private final RetryPolicy retryPolicy = new DefaultRetryPolicy(REQUEST_TIMEOUT, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);


    private boolean useOtherDomain = false;

    public boolean addDeviceCode = true;

//    private boolean useHttps = false;

//    public boolean isUseHttps() {
//        return useHttps;
//    }
//
//    public void setUseHttps(boolean useHttps) {
//        this.useHttps = useHttps;
//    }

    public void setUseOtherDomain(boolean use) {
        this.useOtherDomain = use;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public NetDataJson(NetDataJson.OnNetDataJsonListener listener) {
        this.mListener = listener;
        paramsMap = new HashMap<String, Object>();
    }


    public NetDataJson(NetDataJson.OnStringListener listener, int mType) {
        this.stringListener = listener;
        this.type = mType;
        paramsMap = new HashMap<String, Object>();
    }


    //获取地址
    public String getDomain() {
//        if (isUseHttps()) {
//            if (BuildConfig.LEO_DEBUG) {
//                return SERVER_DOMAIN;
//            } else {
//                return SERVER_DOMAIN.replace("http", "https");
//            }
//        } else {
        return SERVER_DOMAIN;
//        }
    }


    public void clearMap() {
        if (paramsMap != null) {
            paramsMap.clear();
        }
    }

    public void addParam(String key, Object value) {
        this.paramsMap.put(key.trim(), value);
    }


    public void request(String method) {
        if (addDeviceCode)
            paramsMap.put("device_code", GPJApplication.getInstance().getDeviceCode());
        String parms = encodeUrl(paramsMap);
        if (TextUtils.isEmpty(parms)) {
            requestData(url, method);
        } else {
            requestData(url + "?" + parms, method);
        }
    }


    private void requestData(final String... args) {
        cancelTask();
        String finalURL = "";
        String URL = null;
        if (!useOtherDomain) {
            URL = getDomain() + args[0];
        } else {
            URL = args[0];
        }
        NetUtils.getInstance().getAllRequsets().add(URL);
        try {
            final int mothod;


            if (args.length > 1 && args[1].equals("post")) {
                mothod = Request.Method.POST;
                finalURL = CRequest.UrlPage(URL);
                if (finalURL.equals(SERVER_DOMAIN + API.add_recomend_car)) {
                    finalURL = finalURL + "?vip_buy_type=" + postType;
                }
            }else if (args.length > 1 && args[1].equals("delete")) {
                mothod = Request.Method.DELETE;
                finalURL = URL;
            }else if (args.length > 1 && args[1].equals("put")) {
                mothod = Request.Method.PUT;
                finalURL = URL;
            } else {
                mothod = Request.Method.GET;
                finalURL = URL;
            }

            final String finalURL1 = finalURL;
            stringRequest = new StringRequest(mothod, finalURL, new Response.Listener<String>() {
                @Override
                public void onResponse(String result) {
                    Log.d("request", "start--------------------------------");
                    Log.d("request", "URL:" + finalURL1);
                    String s = "";
                    try {
                        String newresult = new String(result.getBytes("ISO-8859-1"), "ISO-8859-1");
                        if (result.equals(newresult)) {
                            s = new String(result.getBytes("ISO-8859-1"), "utf-8");
                        } else {
                            s = result;
                        }

                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    if (mothod == Request.Method.POST) {
                        Log.d("request", "mothod:" + "POST");
                        Log.d("request", "params:" + paramsMap.toString());
                    }else if (mothod == Request.Method.PUT) {
                        Log.d("request", "mothod:" + "PUT");
                        Log.d("request", "params:" + paramsMap.toString());
                    }else if (mothod == Request.Method.DELETE) {
                        Log.d("request", "mothod:" + "DELETE");
                        Log.d("request", "params:" + paramsMap.toString());
                    } else {
                        Log.d("request", "mothod:" + "GET");
                    }


                    Log.d("request", "result:" + s.trim().toString());
                    Log.d("request", "end-----------------------------------");
                    if (type == 0) {
                        String status = "failed";
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (null == jsonObject) {
                                mListener.onDataJsonError("数据异常，请检查网络连接或稍后重试。");
                                return;
                            }
                            status = jsonObject.getString("status");
                            if (!status.equals("success")) {
                                mListener.onDataJsonError(jsonObject.getString("msg"));
                            } else {

                                mListener.onDataJsonUpdate(jsonObject);
                            }

                        } catch (JSONException e) {
                            mListener.onDataJsonError("数据异常，请检查网络连接或稍后重试。");
                        }
                    } else if (type == 1) {
                        stringListener.onDataJsonUpdate(s);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    String error = "";
                    if (volleyError instanceof TimeoutError) {
                        error = "服务超时,请稍后再试。";
                    } else if (volleyError instanceof NoConnectionError) {
                        error = "无网络,请检查网络连接或稍后再试。";
                    } else if (volleyError instanceof NetworkError) {
                        error = "服务端出错,请检查网络连接或稍后再试。";
                    } else if (volleyError instanceof AuthFailureError) {
                        error = "身份验证出错,请稍后再试。";
                    } else if (volleyError instanceof ServerError) {
                        Log.d("request", "params:" + paramsMap.toString());
                        byte[] htmlBodyBytes = volleyError.networkResponse.data;  //回应的报文的包体内容
                        String body = new String(htmlBodyBytes);
                        try {
                            JSONObject jo = new JSONObject(body);
                            error = jo.getString("detail");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        if (TextUtils.isEmpty(error)) {
                            error = "服务器出错,请稍后再试。";
                        }
                    } else {
                        error = volleyError.toString();
                    }


                    if (type == 0) {
                        mListener.onDataJsonError(error);
                    } else if (type == 1) {
                        stringListener.onDataJsonError(error);
                    }
                }
            }) {
                /**
                 * 保存cookie
                 * @param response
                 * @return
                 */
                @Override
                protected Response<String> parseNetworkResponse(NetworkResponse response) {
                        try {
                            Map<String, String> responseHeaders = response.headers;
                            String cook = responseHeaders.get("Set-Cookie");
                            if (!TextUtils.isEmpty(cook)) {
                                String cooks[] = cook.split(";");
                                String sessions[] = cooks[0].split("=");
                                KCookie cookie = new KCookie(sessions[0], sessions[1]);
                                NetUtils.getInstance().setLocalCookie(cookie);
                            }
                        } catch (Exception e) {

                        }
                        ;

                    return super.parseNetworkResponse(response);
                }

                /**
                 * 传入cookie
                 * @return
                 * @throws AuthFailureError
                 */
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    Map<String, String> maps = new HashMap<>();
                    maps.put("app-version", GPJApplication.getInstance().app_version);
                    maps.put("User-Agent", GPJApplication.getInstance().user_agent);
                    maps.put("channel", GPJApplication.getInstance().channel);
                    String cookie = NetUtils.getInstance().getLocalCookie();
                    maps.put("cookie", cookie);
                    maps.put("Content-Type", "application/x-www-form-urlencoded");
                    return maps;
                }

                /**
                 * post数据
                 * @return
                 * @throws AuthFailureError
                 */
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    return postData(paramsMap);
                }
            };
            if (cacheTime > 0) {
                stringRequest.setShouldCache(true);
                stringRequest.setCacheTime(cacheTime);
            }
            stringRequest.setTag(URL);
            stringRequest.setRetryPolicy(retryPolicy);
            NetUtils.getInstance().getRequestQueue().add(stringRequest);
        } catch (Exception e) {
            Utils.LogD("获取数据异常：" + e.getMessage());
        }

    }


    public void cancelTask() {
        if (stringRequest != null)
            //  NetUtils.getInstance().getRequestQueue().cancelAll(tag);
            stringRequest.cancel();
    }

    private String encodeUrl(Map<String, Object> params) {
        if (params == null || params.size() == 0)
            return "";
        StringBuilder sb = new StringBuilder();
        for (String key : params.keySet()) {
            if (params.get(key) != null) {
                String name = params.get(key).toString();
                sb.append(key.trim()).append("=").append(URLEncoder.encode(name)).append("&");
            }
        }
        return sb.toString();
    }

    private Map<String, String> postData(Map<String, Object> params) {
        Map<String, String> datas = new HashMap<String, String>();
        if (params == null || params.size() == 0)
            return datas;

        for (String key : params.keySet()) {
            if (params.get(key) != null) {
                String name = params.get(key).toString();
                datas.put(key, name);
            }
        }
        return datas;
    }


    /**
     * time  秒
     *
     * @param time
     */
    public void setCacheTime(long time) {
        this.cacheTime = time;
    }


    public interface OnNetDataJsonListener {
        void onDataJsonError(String errorMessage);

        void onDataJsonUpdate(JSONObject json);
    }


    //
    public interface OnStringListener {
        void onDataJsonError(String errorMessage);

        void onDataJsonUpdate(String json);
    }


}
